/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import com.jnetx.javax.sip.util.Parametrized;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class ProxyAuthenticateHeaderParser extends ParametrizedHeaderParserBase<ProxyAuthenticateHeaderImpl> {
    private static final Log logger = LogFactory.getLog(ProxyAuthenticateHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public ProxyAuthenticateHeaderImpl createLazily(byte[] data, int start, int end) {
        return new ProxyAuthenticateHeaderImpl(data, start, end);
    }

    public ProxyAuthenticateHeaderImpl[] parse(ProxyAuthenticateHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new ProxyAuthenticateHeaderImpl();
        int startOfData = start;
        startOfData = ByteArrayUtil.firstMissing(data, ' ', startOfData, end);
        if (startOfData == -1)
            fail("Cannot parse the header!", start);
        int endOfPart = ByteArrayUtil.lastMissing(data, ' ', startOfData, end);
        if (endOfPart == -1)
            endOfPart = startOfData;
        else
            endOfPart++;
        final int spcPosition = ByteArrayUtil.firstOccurence(data, ' ', startOfData, endOfPart);
        if (spcPosition == -1)
            throw new ParseException("Cannot parse the scheme in Proxy-Authentication header!", startOfData);
        header.setScheme(new String(data, startOfData, spcPosition - startOfData));
        parseParameters(header, data, spcPosition + 1, endOfPart, ',');
        return new ProxyAuthenticateHeaderImpl[]{header};
    }

//    @Override
//    protected boolean parseSpecificParameter(ProxyAuthenticateHeaderImpl header, String name, String value) throws ParseException {
//        if (name.equals("stale"))
//            header.setParameter(name, value, Parametrized.QuotationType.NONE);
//        else if (name.equals("algorithm"))
//            header.setParameter(name, value, Parametrized.QuotationType.NONE);
//        else
//            return false;
//        return true;
//    }
}
/*
 * $Log$
 */